﻿using AoYing_DeviceCollection.Model;
using Newtonsoft.Json;
using NPOI.SS.Formula.PTG;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static AoYing_DeviceCollection.SmtMachine_Gather;
using static System.Windows.Forms.LinkLabel;

namespace AoYing_DeviceCollection
{
    public partial class MQTEST : Form
    {
        public MQTEST()
        {
            InitializeComponent();
        }

        //private async void button1_Click(object sender, EventArgs e)
        //{

        //    try
        //    {
        //        string numStr = textBox1.Text;
        //        bool isNumeric = int.TryParse(numStr, out _);
        //        bool istrant = checkBox1.Checked;
        //        DateTime startDate = DateTime.Now;
        //        DateTime endDate = DateTime.Now;
        //        if (isNumeric)
        //        {
        //            //获取企业信息IP 地址
        //            DataTable hostTable = CommonHelper.GetDataTable("SELECT hosturl,companyID from sysdatcompany limit 1;");

        //            if (hostTable.Rows.Count == 0)
        //            {
        //                MessageBox.Show("企业信息未维护");

        //            }

        //            string hostPath = hostTable.Rows[0]["hosturl"].ToString();
        //            string dbname = hostTable.Rows[0]["companyID"].ToString();


        //            if (!istrant)
        //            {
        //                for (global::System.Int32 i = 0; i < int.Parse(numStr); i++)
        //                {

        //                    var sendModel = new
        //                    {
        //                        funcname = "MQTestSend",
        //                        body = new
        //                        {
        //                            TestCode = $"编码{(i + 1).ToString("D5")}",
        //                        }
        //                    };

        //                    //发送数据

        //                    var sendJson = JsonConvert.SerializeObject(sendModel);

        //                    HttpHelper.HttpPost($"http://{hostPath}/extend/invoke/?id=DefaultAllMethod&token={dbname}12345678", sendJson);


        //                }
        //                endDate = DateTime.Now;

        //            }
        //            else
        //            {
        //                List<Task> tasks = new List<Task>();

        //                for (global::System.Int32 i = 0; i < int.Parse(numStr); i++)
        //                {

        //                    var sendModel = new
        //                    {
        //                        funcname = "MQTestSend",
        //                        body = new
        //                        {
        //                            TestCode = $"编码{(i + 1).ToString("D5")}",
        //                        }
        //                    };

        //                    //发送数据

        //                    var sendJson = JsonConvert.SerializeObject(sendModel);
        //                    tasks.Add(Task.Run(() => HttpHelper.HttpPost($"http://{hostPath}/extend/invoke/?id=DefaultAllMethod&token={dbname}12345678", sendJson)));

        //                }
        //                await Task.WhenAll(tasks);
        //               endDate = DateTime.Now;

        //            }
        //            TimeSpan timeDifference = endDate - startDate;

        //            // 获取时间差的秒数
        //            double secondsDifference = timeDifference.TotalSeconds;
        //            MessageBox.Show($"发送完成  间隔{secondsDifference}");
        //        }
        //        else
        //        {
        //            MessageBox.Show("请输入纯数字！！！");
        //            textBox1.Text = "";
        //        }
        //    }
        //    catch (Exception ex)
        //    {

        //        MessageBox.Show(ex.Message);
        //    }


        //}
        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string numStr = textBox1.Text;
                bool isNumeric = int.TryParse(numStr, out int totalRequests);
                bool isParallel = checkBox1.Checked;

                if (!isNumeric || totalRequests <= 0)
                {
                    MessageBox.Show("请输入有效的正整数！");
                    textBox1.Text = "";
                    return;
                }

                // 获取企业信息
                DataTable hostTable = CommonHelper.GetDataTable("SELECT hosturl,companyID from sysdatcompany limit 1;");
                if (hostTable.Rows.Count == 0)
                {
                    MessageBox.Show("企业信息未维护");
                    return;
                }

                string hostPath = hostTable.Rows[0]["hosturl"].ToString();
                string dbname = hostTable.Rows[0]["companyID"].ToString();
                string baseUrl = $"http://{hostPath}/extend/invoke/?id=DefaultAllMethod&token={dbname}12345678";

                DateTime startDate = DateTime.Now;

                if (!isParallel)
                {
                    // 顺序执行模式
                    for (int i = 0; i < totalRequests; i++)
                    {
                        var sendModel = new
                        {
                            funcname = "MQTestSend",
                            body = new { TestCode = $"编码{(i + 1).ToString("D5")}" }
                        };

                        string sendJson = JsonConvert.SerializeObject(sendModel);
                        await HttpHelper.HttpPostAsync(baseUrl, sendJson);

                        // 每1000次更新一次进度
                        if (i % 1000 == 0)
                        {
                            UpdateProgress(i, totalRequests);
                        }
                    }
                }
                else
                {
                    // 并行执行模式（分批处理）
                    const int batchSize = 1000; // 每批1000个请求
                    const int maxConcurrent = 50; // 最大并发数50

                    int totalBatches = (int)Math.Ceiling((double)totalRequests / batchSize);

                    for (int batch = 0; batch < totalBatches; batch++)
                    {
                        int start = batch * batchSize;
                        int end = Math.Min((batch + 1) * batchSize, totalRequests);

                        var tasks = new List<Task>();
                        var semaphore = new SemaphoreSlim(maxConcurrent);

                        for (int i = start; i < end; i++)
                        {
                            await semaphore.WaitAsync();

                            int current = i; // 捕获当前值
                            tasks.Add(Task.Run(async () =>
                            {
                                try
                                {
                                    var sendModel = new
                                    {
                                        funcname = "MQTestSend",
                                        body = new { TestCode = $"编码{(current + 1).ToString("D5")}" }
                                    };

                                    string sendJson = JsonConvert.SerializeObject(sendModel);
                                    await HttpHelper.HttpPostAsync(baseUrl, sendJson);

                                }
                                finally
                                {
                                    semaphore.Release();
                                }
                            }));

                            // 每100次更新一次进度
                            if (i % 100 == 0)
                            {
                                UpdateProgress(i, totalRequests);
                            }
                        }

                        await Task.WhenAll(tasks);
                        UpdateProgress(end, totalRequests);
                    }
                }

                DateTime endDate = DateTime.Now;
                TimeSpan timeDifference = endDate - startDate;
                MessageBox.Show($"发送完成！总耗时: {timeDifference.TotalSeconds:F2}秒");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}");
            }
        }

        private void UpdateProgress(int completed, int total)
        {
            // 这里可以更新UI显示进度
            double percentage = (double)completed / total * 100;
            this.Invoke((MethodInvoker)delegate {
                labelProgress.Text = $"进度: {completed}/{total} ({percentage:F1}%)";
                progressBar1.Value = (int)percentage;
            });
        }
    }
}
